package mfuny.ggongal.admin.https;

import java.util.HashMap;

import mfuny.ggongal.admin.http.HttpPostSender;

import org.json.simple.JSONObject;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class GGEncoder {
	
	public static String send(String url, HashMap<String, Object> params ) throws Exception {
		return sendWork(url, params, "UTF-8");
	}
	
	public static String send(String url, HashMap<String, Object> params, String encode) throws Exception {
		return sendWork(url, params, encode);
	}
	
	@SuppressWarnings("unchecked")
	private static String sendWork(String url, HashMap<String, Object> params, String encode) throws Exception {
		JsonCreater jc = new JsonCreater();
		JSONObject json = jc.getJsonByMap(params);
		json.put("cccctttt", System.currentTimeMillis());
		String bStr = encodeForJson(json);
		
		HashMap<String, String> postParam = new HashMap<String, String>();
		postParam.put("ggongal", bStr);
		
		String result = new HttpPostSender().send(url, postParam, encode);
		return GGDecoder.decode(result);
	}
	
	public static String encodeForJson(JSONObject json) throws Exception {
		Neutral neu = new Neutral();
		String jsonStr = json.toJSONString();
		String bStr = neu.change(jsonStr);
		bStr = neu.ternOver(bStr);
		bStr = new String(neu.change(bStr));
		int ran = (int)(Math.random() * 100);
		String ranStr = (ran < 10 ? "0" : "") + ran;
		String ope2h = ranStr + neu.getOpe2h()[ran];
		bStr = neu.insertStr(bStr, ope2h);
		bStr = neu.lastTurnOver(bStr);
		
		return bStr;
	}
	
//	public static void main(String[] args) throws Exception {
//		String url = "http://192.168.0.92:8080/ggongal_admin/httpUser.ga";
//		HashMap<String, Object> postParam = new HashMap<String, Object>();
//		postParam.put("tag", "user_addGgong");
//		postParam.put("id", "hkpark");
//		postParam.put("ggong", "-1000");
//		postParam.put("reason", "아이템 구매 테스트");
//		String result = send(url, postParam, "UTF-8");
//		System.out.println(result);
//	}
	
	public static void main(String[] args) throws Exception {
		String url = "http://192.168.0.92:8080/ggongal_admin/httpUser.ga";
		String a ="{\"id\":\"hkpark\",\"reason\":\"한글 테스트 1234 abcd\",\"tag\":\"user_addGgong\",\"ggong\":-500}";
		
		BASE64Encoder en = new BASE64Encoder();
		BASE64Decoder de = new BASE64Decoder();
//		String jsonStr = new JsonCreater().getJsonByMap(a).toJSONString();
		System.out.println("jsonStr : "+a);
		String result = en.encode(a.getBytes());
		System.out.println("인코딩 : "+result);
		byte[] by = de.decodeBuffer(result);
		System.out.println("디코딩 : "+ new String(by));
	}
}
